##########################################################################################

library(data.table)
library(optparse)

##########################################################################################

option_list <- list(
    make_option(c("--bam_qc_file"), type = "character"),
    make_option(c("--base_line_file"), type = "character"),
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
    bam_qc_file <- "~/20220915_gastric_multiple/rna_batch1/results/Qc/Bam_MutipleQc/multiqc_report.tsv"
    base_line_file <- "~/20220915_gastric_multiple/config/Tumor_Normal_RNA.tsv"
    out_path <- "~/20220915_gastric_multiple/rna_batch1/results/Qc/Bam_MutipleQc/"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)


bam_qc_file <- opt$bam_qc_file
out_path <- opt$out_path
base_line_file <- opt$base_line_file

###########################################################################################

dat_qc <- data.frame(fread(bam_qc_file))
info <- data.frame(fread(base_line_file))

###########################################################################################
col_names <- c("ID" , "Sample" , "From" , "Class" )

use_col <- c("ID" , "Tumor" , "From" , "Class" )
dat_tumor <- info[,use_col]
colnames(dat_tumor) <- col_names

use_col <- c("ID" , "Normal" , "From")
dat_normal <- unique(info[,use_col])
dat_normal$Class <- "Normal"
colnames(dat_normal) <- col_names

dat_final <- rbind(dat_tumor , dat_normal)

###########################################################################################
dat_qc_merge <- merge( dat_final , dat_qc , by.x = "Sample" , by.y = "Sample.Name" )

use_col <- c("Sample" , "ID" , "From" , "Class" , "X..mRNA" , "STRAND_BALANCE" , "MEAN_READ_LENGTH" , "X..Aligned" , "X..Dups" )
col_names <- c("Sample" , "ID" , "From" , "Class" , "mRNA_Rate" , "STRAND_BALANCE" , "MEAN_READ_LENGTH" , "Aligned_Rate" , "Dups_Rate" )

dat_qc_merge <- dat_qc_merge[,use_col]
colnames(dat_qc_merge) <- col_names

out_name <- paste0( out_path , "/multiqc_report.mergeInfo.tsv" )
write.table( dat_qc_merge , out_name , sep = "\t" , quote = F , row.names = F )